#! /usr/bin/perl

use CGI ':standard' ;
use CGI::Carp qw(fatalsToBrowser) ;
use Cwd ;
use Archive::Zip ;
use DBQueries;

my $files_location ;
my @ID = ();
my @fileholder ;
my $zip;

my $username = param('username');
my $group_name = param('groupName');
my $file_id = param('fileID');
my $file_owner= param('fileOwner');

#set file location
$files_location = Cwd->getcwd() . "/files";

#declare scalar to hold name of file to be downloaded
my $downloaded_name;

#declare array to hold all file names
my @names_to_download;

#obtain ID's
#determine if one single file shoudl be downloaded
if($file_id ne ""){
	
	#in this case we are only dealing with one file, therefore only add one file to the arrays
	my $name_to_download = DBQueries::getFileName($file_id);
	
	
	$name_to_download =~ m/(.+)(\....)$/;
	
	my $file_to_download = "$file_id" . "$2";
	
	download("files/$file_to_download", $name_to_download);
}

#otherwise download a batch multiple files
else{
	
	@names_to_download = DBQueries::getGroupFileNames($group_name);
	
	$zip = $group_name . "\.zip";
	
	#loop through each name and get ID from owner
	foreach $current_file(@names_to_download){
	
		$current_id = DBQueries::getFileID($file_owner, $current_file);
		
		#math for file ending
		$current_file =~ m/(.+)(\....)$/;
		
		$current_id .= "$2";
		
		#add to array of file ids
		push(@ID, $current_id);
	}	
	
	compress( @ID ) ;

	download( $zip, $zip ) ;
}

sub download
{
	#obtain parameters
	#system file
	my $system_name = $_[0];
	#target name
	my $target_name = $_[1];
	
	open( DLFILE, "<$system_name" ) || Error( 'open', 'file' ) ;
	@fileholder = <DLFILE> ;
	close (DLFILE) || Error ( 'close', 'file' ) ;
		
	print "Content-Type:application/x-download\n" ;
	print "Content-Disposition:attachment;filename=$target_name\n\n" ;
	print @fileholder ;
}

sub compress
{
	my @add = @_ ;
	$obj = Archive::Zip->new() ;
	foreach my $files ( @add )
	{
		$obj->addFile( "files/$files" ) ;
	}
	if( $obj->writeToFileNamed( "$zip" ) != AZ_OK )
	{
		print "Error in archive creation!" ;
	}
	else
	{
		print "Archive created successfully!" ;
	}
}

sub Error
{
	print "Content-type: text/html\n\n" ;
	print "The server can't $_[0] the $_[1]: $! \n" ;
	exit ;
}